package com.zjl.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class HTMLtoPDFConverter {
        public static byte[] convertToPDF(String html) throws Exception {
            Document document = new Document();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);

            document.open();

            InputStream inputStream = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, inputStream);

            document.close();

            return outputStream.toByteArray();
        }

    public static void main(String[] args) {
        try {
            String htmlString = "<html><body><h1>Example HTML to PDF conversion</h1></body></html>";
            byte[] pdfBytes = convertToPDF(htmlString);

            // 保存或输出 PDF 字符串
            // ...
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}